package com.example.notelite;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.CharArrayBuffer;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

public class DbRoom extends SQLiteOpenHelper {
        public final String TABLENAME="_table";
        public final String ID="_id";
        public final String CONTENT="content";
        public final String CTIME="create_time";
        public final String STIME="save_time";
        SQLiteDatabase db;

    public DbRoom(@Nullable Context context) {
        super(context, "notes", null, 1);
        db=this.getWritableDatabase();
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE "+TABLENAME+"("
                +ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"
                +CONTENT+" TEXT NOT NULL,"
                +CTIME+" TEXT,"+
                STIME+" TEXT )");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
    //插入数据
    public long insertRecord(String record,String ctime){
        ContentValues contentValues=new ContentValues();
        contentValues.put(CONTENT,record);
        contentValues.put(CTIME,ctime);
        return db.insert(TABLENAME,null,contentValues);


    }
    //更新数据
    public int updateRecord(String id,String record,String ctime){
        ContentValues contentValues=new ContentValues();
        contentValues.put(ID,id);
        contentValues.put(CONTENT,record);
        contentValues.put(CTIME,ctime);
       return db.update(TABLENAME,contentValues,"id=?",new String[]{id});
    }
    public void delrecord(String id){
        db.delete(TABLENAME,"id=?",new String[]{id});
    }
    public List<record> queryRecord(){
        Cursor cursor=db.query(TABLENAME,null,null,null,null,null,CTIME+" desc");
        List<record> recordsList=new ArrayList<>();
        if(recordsList!=null) {
            while(cursor.moveToNext()){
                String id=String.valueOf(cursor.getInt(cursor.getColumnIndex(ID)));
                String record=String.valueOf(cursor.getString(cursor.getColumnIndex(CONTENT)));
                String create_time=String.valueOf(cursor.getString(cursor.getColumnIndex(CTIME)));
                record record1=new record(id,record,create_time);
                recordsList.add(record1);
            }
            cursor.close();
        }
        return recordsList;
        }


}
